package com.etoak.util;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Java Bean 校验工具类
 */
public class ValidatorUtil {

    private static Validator validation;

    static {

        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validation =  factory.getValidator();

    }
    public static void validate(Object object) {

        Set<ConstraintViolation<Object>> violations = validation.validate(object);

        if (CollectionUtils.isNotEmpty(violations)) {
            List<String> messageList = violations.stream().map(v -> {
                String field = v.getPropertyPath().toString();
                String message = v.getMessage();
                return StringUtils.join(field, message);
            }).collect(Collectors.toList());

            throw new RuntimeException(StringUtils.join(messageList, ";"));
        }


    }




}
